﻿using NVelocity;
using NVelocity.App;
using NVelocity.Exception;
using NVelocity.Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Automation.Hander
{
    class NVelocityHelper
    {
        protected VelocityContext context;
        protected Template template;
        protected string templateFile;

        /// <summary>
        /// 存放键值的字典内容
        /// </summary>
        private Dictionary<string, object> KeyObjDict = new Dictionary<string, object>();


        /// <summary>
        /// 添加一个键值对象
        /// </summary>
        /// <param name="key">键，不可重复</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        public NVelocityHelper AddKeyValue(string key, object value)
        {
            if (!KeyObjDict.ContainsKey(key))
            {
                KeyObjDict.Add(key, value);
            }
            return this;
        }
        /// <summary>
        /// 初始化模板引擎
        /// </summary>
        protected virtual void InitTemplateEngine()
        {
            try
            {
                //Velocity.Init(NVELOCITY_PROPERTY);
                VelocityEngine templateEngine = new VelocityEngine();
                templateEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");

                templateEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
                templateEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");

                //如果设置了FILE_RESOURCE_LOADER_PATH属性，那么模板文件的基础路径就是基于这个设置的目录，否则默认当前运行目录
                templateEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory);

                templateEngine.Init();

                template = templateEngine.GetTemplate(templateFile);
            }
            catch (ResourceNotFoundException re)
            {
                string error = string.Format("Cannot find template " + templateFile);

                // LogTextHelper.Error(error);
                throw new Exception(error, re);
            }
            catch (ParseErrorException pee)
            {
                string error = string.Format("Syntax error in template " + templateFile + ":" + pee.StackTrace);
                //LogTextHelper.Error(error);
                throw new Exception(error, pee);
            }
        }
        /// <summary>
        /// 初始化上下文的内容
        /// </summary>
        private void InitContext()
        {
            context = new VelocityContext();
            foreach (string key in KeyObjDict.Keys)
            {
                context.Put(key, KeyObjDict[key]);
            }
        }

        /// <summary>
        ///根据模板创建输出的文件,并返回生成的文件路径
        /// </summary>
        public virtual string ExecuteFile()
        {
            string fileName = "";
            if (template != null)
            {
                string filePath = "";
                fileName = "";

                if (!string.IsNullOrEmpty(filePath) && !Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                //LogTextHelper.Debug(string.Format("Class file output path:{0}", fileName));
                InitContext();
                using (StreamWriter writer = new StreamWriter(fileName, false))
                {
                    template.Merge(context, writer);
                }
            }
            return fileName;
        }
        /// <summary>
        /// 根据模板输出字符串内容
        /// </summary>
        /// <param name="templateFile"></param>
        /// <returns></returns>
        public string ExecuteString()
        {
            InitContext();
            System.IO.StringWriter writer = new System.IO.StringWriter();
            template.Merge(context, writer);
            return writer.GetStringBuilder().ToString();
        }


        /// <summary>
        /// 合并字符串的内容
        /// </summary>
        /// <returns></returns>
        public string ExecuteMergeString(string inputString)
        {
            VelocityEngine templateEngine = new VelocityEngine();
            templateEngine.Init();

            InitContext();

            System.IO.StringWriter writer = new System.IO.StringWriter();
            templateEngine.Evaluate(context, writer, "mystring", inputString);

            return writer.GetStringBuilder().ToString();
        }

        private void btnMergeString_Click(object sender, EventArgs e)
        {
            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            builder.Append(
                "${Title}\r\n" +
                "$Content\r\n" +
                "$Digest\r\n" +
                "$Author\r\n" +
                "$Keyword\r\n" +
                "$DateTime\r\n");
            NVelocityHelper adapter = new NVelocityHelper();
            adapter.AddKeyValue("Title", "标题").
                AddKeyValue("Content", "内容").
                AddKeyValue("Digest", "摘要").
                AddKeyValue("Author", "作者").
                AddKeyValue("Keyword", "关键词").
                AddKeyValue("DateTime", DateTime.Now);
            // this.txtCode.Text = adapter.ExecuteMergeString(builder.ToString());
        }



    }
}
